<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2015/10/28
 * Time: 10:14
 */

namespace Wap;
use Common\Model\LogModel;
use Common\Model\UtilsModel;
use Common\Model\WeixinModel;
use Think\Controller;
use Common\Model\UserModel;
class BaseController extends Controller {

    protected $smarty=null;
    protected $isWechat=0;
    public function _empty(){
        $this->callMethod();
    }


    public function wxLogin(){
        $openid     = isset($_REQUEST['openid']) ? $_REQUEST['openid'] : null;
        $redirect   = isset($_REQUEST['redirect']) ? $_REQUEST['redirect'] : UtilsModel::getFullDomain(). $_SERVER['REQUEST_URI'];
        $gourl =  urlencode($redirect);
        header("Content-Type: text/html;charset=utf-8");
        $string = urldecode($_SERVER['QUERY_STRING']);
        $ret = array();
        @parse_str($string, $ret);

        //若获取不到openid
        if (!$ret['openid']) {
            $url = WECHAT_AUTHORIZATION_URI."backurl=" . urlencode($gourl);
            header("Location:" . $url);
            die;
        }

        //若获取不到nickname
        if (!$ret['nickname']) {
            $url = WECHAT_AUTHORIZATION_GET_USERINFO_URI."backurl=" . urlencode($gourl);
            header("Location:" . $url);
            die;
        }

        //复制获取openid
        session('openid',$ret['openid']);
        session('unionid',$ret['unionid']);
        $res = UserModel::wechatLogin($ret['openid'], 2, $ret['unionid'], $ret['nickname'], $ret['headimgurl'], $ret['sex'], $ret['subscribe_time']);
        $userinfo = UserModel::getUser($res['uid']);
        if (strcmp($ret['nickname'],$userinfo['data']['nickname'])!=0){//如昵称有修改则更新
            UserModel::getInstance()->where("uid={$res['uid']}")->setField('nickname',$ret['nickname']);
            $userinfo['data']['nickname']=$ret['nickname'];
        }


        self::resetUserSessions($userinfo['data']);
        $redirect = session('redirect');
        session('redirect',null);
        session('starLogin',1);
        header("Location: ".$redirect);
        die;
    }



    /**
     *
     * Author: shijy
     */
    function _initialize(){
        UtilsModel::checkMaintenance();

        $user_agent = $_SERVER['HTTP_USER_AGENT'];
        $this->isWechat = 0;
        if(strpos($user_agent, 'MicroMessenger') !== false ) {
            UtilsModel::disableClientAndTip(ENABLE_WEIXIN);


                $lastRedirect = session('redirect');
                if (!$lastRedirect) {
                    if(!IS_AJAX) {
                        session('redirect', $_SERVER['REQUEST_URI']);
                    }
                    else{
                        session('redirect', $_SERVER['HTTP_REFERER']);
                    }
                }


            $this->isWechat = 1;
            if(!session('uid') || !session('starLogin')) {
                $this->wxLogin();
            }
        }
        else{
            UtilsModel::disableClientAndTip(ENABLE_WAP);
        }


        $this->smarty=getSmarty();

        //全局传用户信息
        $this->smarty->assign('userinfo',array());
        if(session('uid')){
            if(CONTROLLER_NAME == 'Events' && ACTION_NAME == 'index') session('newEvent',0);
            if(CONTROLLER_NAME == 'PointMall' && ACTION_NAME == 'index') session('newPointMall',0);
            if(CONTROLLER_NAME == 'Notice' && ACTION_NAME == 'message') session('newNotice',0);

                $rett=UserModel::getUserChangeful(session('uid'));
                $userChangeful=$rett['data'];

            if(!is_null($userChangeful)){
                $uinfo['point'] 		= $userChangeful['point'];
                $uinfo['money'] 		= $userChangeful['money'];
                $uinfo['level'] 		= $userChangeful['level'];
                $uinfo['consumeMoney']  = $userChangeful['consumeMoney'];
                $uinfo['EXP']  			= $userChangeful['EXP'];
                self::resetUserSessions( $userChangeful );
            }

          //  session('tip',S('tip_'.session('uid')));
            $this->smarty->assign('userinfo',session());
        }
        if(!IS_AJAX){
        //    S('tip_'.session('uid'),null);
        }

        //微信分享
        $this->smarty->assign('isWechat',$this->isWechat);
        if($this->isWechat){
            $wxReturn = WeixinModel::getSignPackage();
            if($wxReturn['status']==0){
                $this->smarty->assign('wxSign',$wxReturn['data']);
            }
        }

        if(!session('lastJoinTime')) session('lastJoinTime', time()) ;

        if(session('uid')){
            if(UserModel::userSign(session('uid'))!==false){
                session('sign',1);
            };
        }


    }



    /**
     * 重置session的参数
     * User: Rick.Sun.<sunwgjj@126.com>
     * Return: void
     * Address: 浙江宣逸网络科技有限公司
     * @param $data
     */
    function resetUserSessions($data){
        foreach ($data as $k => $v) {
            session($k, $v);
        }
    }

    public function callMethod(){

        //检查公司专属函数，检查平台专属函数
        $method=ACTION_NAME.'_'.CURRENT_COMPANY;
        if(!method_exists($this,$method )){
            $method=ACTION_NAME.'_'.OTHER_PART;
            if(!method_exists($this,$method )) {
                //$this->error('未定义的方法:' . $method);
                $method=ACTION_NAME.'_default';
                if(!method_exists($this,$method )) {
                    $this->error('未定义的方法:' . $method);
                }
            }
        }

        $ref_class = new \ReflectionClass($this);
        $instance  = $ref_class->newInstance();
        $method = $ref_class->getmethod($method);
        $method->setAccessible(true);
        $method->invoke($instance);
    }


}